<!--
 * @Author: Rain
 * @Date: 2024/01/15 11:50:26
 * @LastEditTime: 2024/01/18 15:00:19
 * @Description: Do Something
-->
<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div class="w-full flex items-center justify-end">
        <!-- 搜索 -->
        <label class="el-form-item-label">名称</label>
        <el-input
          v-model="query.partnerName"
          class="filter-item"
          clearable
          placeholder="名称"
          style="width: 185px"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
        <crudOperation :permission="permission" />
      </div>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :title="crud.status.title"
        :visible.sync="dialogVisible"
        width="600px"
      >
        <el-form
          ref="form"
          :model="form"
          label-width="80px"
          size="small"
        >
          <el-form-item
            :rules="{ required: true, message: '请输入名称', trigger: 'blur' }"
            label="名称"
            prop="partnerName"
          >
            <el-input
              v-model="form.partnerName"
              class="w-full"
              placeholder="请输入名称"
            />
          </el-form-item>
          <el-form-item
            :rules="{ required: true, message: '请选择星级', trigger: 'blur' }"
            label="星级"
            prop="starNum"
          >
            <el-select
              v-model="form.starNum"
              class="w-full"
              clearable
              filterable
              placeholder="请选择"
              value-key
            >
              <el-option
                v-for="item in dict.partner_level"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="管理员" prop="" :rules="{ required: true, message: '请选择管理员', trigger: 'blur' }">
            <el-select
              v-model="selectUserList"
              :remote-method="remoteMethod"
              class="w-full"
              collapse-tags
              filterable
              multiple
              placeholder="请选择"
              remote
            >
              <el-option
                v-for="item in wxList"
                :key="item.id"
                :label="`${item.nickname}(${item.mobile})`"
                :value="item.mobile"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="成员">
            <el-select
              v-model="selectUserList"
              :remote-method="remoteMethod"
              class="w-full"
              collapse-tags
              filterable
              multiple
              placeholder="请选择"
              remote
            >
              <el-option
                v-for="item in wxList"
                :key="item.id"
                :label="`${item.nickname}(${item.mobile})`"
                :value="item.mobile"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="w-full flex flex-col items-end">
              <el-table
                :data="memberList"
                :max-height="300"
                class="w-full"
              >
                <el-table-column
                  label="#"
                  type="index"
                />
                <el-table-column
                  label="微信名"
                  prop="nickName"
                >
                  <template slot-scope="{row}">{{ row.nickName || row.nickname }}</template>
                </el-table-column>
                <el-table-column
                  label="姓名"
                  prop="realName"
                />
                <el-table-column
                  label="手机号"
                  prop="mobile"
                />
                <el-table-column label="操作">
                  <template slot-scope="{ row }">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete(row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            style="margin-right: 10px"
            type="default"
            @click="dialogVisible = false"
          >取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="submitAction"
          >确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="mini"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          label="名称"
          prop="partnerName"
        >
          <template slot-scope="{ row }">
            <span
              style="cursor: pointer; color: rgb(120, 120, 229)"
              @click="handleView(scope.row)"
              v-text="row.partnerName"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="星级"
          prop="starNum"
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
        />
        <el-table-column
          v-if="checkPer(['admin', 'disPartner:edit', 'disPartner:del'])"
          align="center"
          label="操作"
          width="150px"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDisPartner, { getDisPartnerUser } from '@/api/disPartner'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { addOrder } from '@/api/disChangeApply'
import { Message } from 'element-ui'

const defaultForm = {
  partnerId: null,
  partnerName: null,
  starNum: null,
  createTime: null,
  createUser: null,
  updateTime: null,
  updateUser: null,
  partnerStatus: null
}
export default {
  name: 'DisPartner',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['partner_level'],
  cruds() {
    return CRUD({
      title: '城市合伙人',
      url: 'api/disPartner',
      idField: 'partnerId',
      sort: 'partnerId,desc',
      crudMethod: { ...crudDisPartner }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'disPartner:add'],
        edit: ['admin', 'disPartner:edit'],
        del: ['admin', 'disPartner:del']
      },
      queryTypeOptions: [{ key: 'partnerName', display_name: '名称' }],
      userList: [],
      selectUserList: [],
      keyWords: '',
      page: 0,
      timer: null,
      dialogVisible: false,
      memberList: []
    }
  },
  computed: {
    total() {
      return this.memberList.length
    },
    wxList() {
      return this.userList.filter((item) => item.mobile)
    }
  },
  watch: {
    selectUserList(val) {
      const list = this.userList.concat(this.memberList)
      this.memberList = list.filter((item) => val.includes(item.mobile) || val.includes(item.id))
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeToAdd]() {
      this.dialogVisible = true
    },
    [CRUD.HOOK.beforeToEdit]({ form: { partnerId }}) {
      if (!partnerId) {
        this.dialogVisible = true
        this.memberList = []
        return
      }
      // 获取成员
      getDisPartnerUser({ partnerId }).then((res) => {
        const { content } = res
        this.selectUserList = content.map((item) => item.mobile)
        this.memberList = content
        this.dialogVisible = true
        this.form['defaultList'] = content
      })
    },
    getWXUser() {
      this.$http
        .get('api/wxUser', {
          params: { page: this.page, size: 500000000, mobile: this.keyWords }
        })
        .then((_) => {
          const { content } = _
          this.userList = content
        })
    },
    remoteMethod(e) {
      if (!e) return
      this.keyWords = e
      this.userList = []
      this.getWXUser()
    },
    handleDelete(row) {
      const { id } = row
      const index = this.selectUserList.findIndex((item) => item === id)
      this.selectUserList.splice(index, 1)
      // this.memberList = this.memberList.filter((item) => this.selectUserList.includes(item.id))
    },
    async submitAction() {
      const { partnerId } = this.form
      const disPartnerUserList = this.memberList.map((item) => {
        const { nickname: nickName, openId, mobile, realName } = item
        return {
          nickName,
          openId,
          mobile,
          realName
        }
      })
      const params = {
        applyContent: JSON.stringify({
          partnerName: this.form.partnerName,
          disPartnerUserList,
          starNum: this.form.starNum,
          partnerId,
          defaultList: this.form.defaultList || []
        }),
        applyType: 7,
        applyStatus: -1,
        refuseMsg: ''
      }
      addOrder(params).then((_) => {
        Message.success('操作成功!')
        this.dialogVisible = false
      })
    },
    handleView(row) {
      console.log(row)
    }
  }
}
</script>

<style scoped></style>
